﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Admin.Core.Service.sys.Dict/SysDictTypeServiceImpl 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       SysDictTypeServiceImpl
* 创建时间：  2025/6/4 15:46:42
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using MapsterMapper;
using SSPivot.Admin.Core.DbModel.sys;
using SSPivot.Admin.Core.Service.sys.Dict.Dto;
using SSPivot.AspNetCore.Services;
using SSPivot.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using SSPivot.Admin.Core.Repository;
using Mapster;
using Microsoft.EntityFrameworkCore;

namespace SSPivot.Admin.Core.Service.sys.Dict
{
    /// <summary>
    /// 数据字典类型服务
    /// </summary>
    public class SysDictTypeServiceImpl : ApplicationService, ISysDictTypeService
    {
        #region 接口注入
        public ISSPivotRepository<sys_dict_type> DictTypeRepository { get; set; }
        public ISSPivotRepository<sys_dict> DictRepository { get; set; }
        #endregion

        #region 服务

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SysDictTypeDto> GetAsync(long id)
        {
            var result = await DictTypeRepository.GetAsync(id);
            return result.Adapt<SysDictTypeDto>();
        }
        /// <summary>
        /// 获取数量 
        /// </summary>
        /// <returns></returns>
        public async Task<int> CountAsync(QuerySysDictTypeRequest model)
        {
            return await DictTypeRepository.QueryNoTracking(this.BuildSearch(model)).CountAsync();
        }
        /// <summary>
        /// 是否存在 
        /// </summary>
        /// <returns></returns>
        public async Task<bool> AnyAsync(QuerySysDictTypeRequest model)
        {
            return await DictTypeRepository.QueryNoTracking(this.BuildSearch(model)).AnyAsync();
        }
        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<List<SysDictTypeDto>> QueryAsync(QuerySysDictTypeRequest model)
        {
            var data = await DictTypeRepository.QueryNoTracking(this.BuildSearch(model), this.BuildSort(model)).ToListAsync();
            if (data == null) return null;
            return data.Adapt<List<SysDictTypeDto>>();
        }

        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>  
        public async Task<(List<SysDictTypeDto>, PageResult)> PageAsync(QuerySysDictTypeRequest model, PageResult page)
        {
            var data = await DictTypeRepository.QueryNoTracking(this.BuildSearch(model), this.BuildSort(model), page).ToListAsync();
            if (data == null) return (null, page);
            return (data.Adapt<List<SysDictTypeDto>>(), page);
        }


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<long> AddAsync(SysDictTypeDto input)
        {

            if (await DictTypeRepository.QueryNoTracking(a => a.Name == input.Name).AnyAsync())
            {
                throw ServiceResult.Exception("字典类型已存在");
            }

            if (input.Code.IsNotNullOrEmpty() && await DictTypeRepository.QueryNoTracking(a => a.Code == input.Code).AnyAsync())
            {
                throw ServiceResult.Exception("字典类型编码已存在");
            }

            var entity = Mapper.Map<sys_dict_type>(input);
            if (entity.Sort == 0)
            {
                var sort = await DictTypeRepository.QueryNoTracking().MaxAsync(a => a.Sort);
                entity.Sort = sort + 1;
            }
            await DictTypeRepository.AddAsync(entity);
            return entity.Id;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateAsync(SysDictTypeDto input)
        {
            var entity = await DictTypeRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ServiceResult.Exception("字典类型不存在");
            }

            if (await DictTypeRepository.QueryNoTracking(a => a.Id != input.Id && a.Name == input.Name).AnyAsync())
            {
                throw ServiceResult.Exception("字典类型已存在");
            }

            if (input.Code.IsNotNullOrEmpty() && await DictTypeRepository.QueryNoTracking(a => a.Id != input.Id && a.Code == input.Code).AnyAsync())
            {
                throw ServiceResult.Exception("字典类型编码已存在");
            }

            Mapper.Map(input, entity);
            await DictTypeRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 彻底删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public virtual async Task DeleteAsync(long id)
        {

            //删除字典数据
            await DictRepository.QueryIgnoreQueryFilters(a => a.DictTypeId == id).ExecuteDeleteAsync();

            //删除数据字典类型
            await DictTypeRepository.QueryIgnoreQueryFilters(e => e.Id == id).ExecuteDeleteAsync();

        }

        /// <summary>
        /// 批量彻底删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>

        public virtual async Task BatchDeleteAsync(long[] ids)
        {
            //删除字典数据
            await DictRepository.QueryIgnoreQueryFilters(a => ids.Contains(a.DictTypeId)).ExecuteDeleteAsync();

            //删除数据字典类型
            await DictTypeRepository.QueryIgnoreQueryFilters(a => ids.Contains(a.Id)).ExecuteDeleteAsync();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public virtual async Task SoftDeleteAsync(long id)
        {
            //删除字典数据
            await DictRepository.Query(a => a.DictTypeId == id).ExecuteDeleteAsync();

            //删除数据字典类型
            await DictTypeRepository.DeleteAsync(id);

        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>

        public virtual async Task BatchSoftDeleteAsync(long[] ids)
        {
            //删除字典数据
            await DictRepository.Query(a => ids.Contains(a.DictTypeId)).ExecuteDeleteAsync();

            //删除数据字典类型
            await DictTypeRepository.Query(a => ids.Contains(a.Id)).ExecuteDeleteAsync();
        }
        #endregion


        #region private
        private Expression<Func<sys_dict_type, bool>> BuildSearch(QuerySysDictTypeRequest model)
        {
            Expression<Func<sys_dict_type, bool>> whereCondition = e => true;

            if (model.Key.IsNotNullOrWhiteSpace())
                whereCondition = whereCondition.And(e => e.Name.Contains(model.Key) || e.Code.Contains(model.Key));
            //if (model.ParentId.HasValue)
            //    whereCondition = whereCondition.And(x => x.par == model.ParentId);

            return whereCondition;
        }

        private Dictionary<Expression<Func<sys_dict_type, dynamic>>, SortType> BuildSort(QuerySysDictTypeRequest model)
        {
            var orderBy = new Dictionary<Expression<Func<sys_dict_type, dynamic>>, SortType>();

            orderBy.Add(e => e.Sort, SortType.Asc);
            orderBy.Add(e => e.Id, SortType.Desc);
            return orderBy;
        }

        #endregion
    }
}
